home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / random.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  25KB  |  783 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Random variable generators.
  5.  
  6.     integers
  7.     --------
  8.            uniform within range
  9.  
  10.     sequences
  11.     ---------
  12.            pick random element
  13.            pick random sample
  14.            generate random permutation
  15.  
  16.     distributions on the real line:
  17.     ------------------------------
  18.            uniform
  19.            triangular
  20.            normal (Gaussian)
  21.            lognormal
  22.            negative exponential
  23.            gamma
  24.            beta
  25.            pareto
  26.            Weibull
  27.  
  28.     distributions on the circle (angles 0 to 2pi)
  29.     ---------------------------------------------
  30.            circular uniform
  31.            von Mises
  32.  
  33. General notes on the underlying Mersenne Twister core generator:
  34.  
  35. * The period is 2**19937-1.
  36. * It is one of the most extensively tested generators in existence.
  37. * Without a direct way to compute N steps forward, the semantics of
  38.   jumpahead(n) are weakened to simply jump to another distant state and rely
  39.   on the large period to avoid overlapping sequences.
  40. * The random() method is implemented in C, executes in a single Python step,
  41.   and is, therefore, threadsafe.
  42.  
  43. '''
  44. from __future__ import division
  45. from warnings import warn as _warn
  46. from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType
  47. from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
  48. from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
  49. from os import urandom as _urandom
  50. from binascii import hexlify as _hexlify
  51. __all__ = [
  52.     'Random',
  53.     'seed',
  54.     'random',
  55.     'uniform',
  56.     'randint',
  57.     'choice',
  58.     'sample',
  59.     'randrange',
  60.     'shuffle',
  61.     'normalvariate',
  62.     'lognormvariate',
  63.     'expovariate',
  64.     'vonmisesvariate',
  65.     'gammavariate',
  66.     'triangular',
  67.     'gauss',
  68.     'betavariate',
  69.     'paretovariate',
  70.     'weibullvariate',
  71.     'getstate',
  72.     'setstate',
  73.     'jumpahead',
  74.     'WichmannHill',
  75.     'getrandbits',
  76.     'SystemRandom']
  77. NV_MAGICCONST = 4 * _exp(-0.5) / _sqrt(2)
  78. TWOPI = 2 * _pi
  79. LOG4 = _log(4)
  80. SG_MAGICCONST = 1 + _log(4.5)
  81. BPF = 53
  82. RECIP_BPF = 2 ** (-BPF)
  83. import _random
  84.  
  85. class Random(_random.Random):
  86.     """Random number generator base class used by bound module functions.
  87.  
  88.     Used to instantiate instances of Random to get generators that don't
  89.     share state.  Especially useful for multi-threaded programs, creating
  90.     a different instance of Random for each thread, and using the jumpahead()
  91.     method to ensure that the generated sequences seen by each thread don't
  92.     overlap.
  93.  
  94.     Class Random can also be subclassed if you want to use a different basic
  95.     generator of your own devising: in that case, override the following
  96.     methods: random(), seed(), getstate(), setstate() and jumpahead().
  97.     Optionally, implement a getrandbits() method so that randrange() can cover
  98.     arbitrarily large ranges.
  99.  
  100.     """
  101.     VERSION = 3
  102.     
  103.     def __init__(self, x = None):
  104.         '''Initialize an instance.
  105.  
  106.         Optional argument x controls seeding, as for Random.seed().
  107.         '''
  108.         self.seed(x)
  109.         self.gauss_next = None
  110.  
  111.     
  112.     def seed(self, a = None):
  113.         '''Initialize internal state from hashable object.
  114.  
  115.         None or no argument seeds from current time or from an operating
  116.         system specific randomness source if available.
  117.  
  118.         If a is not None or an int or long, hash(a) is used instead.
  119.         '''
  120.         if a is None:
  121.             
  122.             try:
  123.                 a = long(_hexlify(_urandom(16)), 16)
  124.             except NotImplementedError:
  125.                 import time as time
  126.                 a = long(time.time() * 256)
  127.             except:
  128.                 None<EXCEPTION MATCH>NotImplementedError
  129.             
  130.  
  131.         None<EXCEPTION MATCH>NotImplementedError
  132.         super(Random, self).seed(a)
  133.         self.gauss_next = None
  134.  
  135.     
  136.     def getstate(self):
  137.         '''Return internal state; can be passed to setstate() later.'''
  138.         return (self.VERSION, super(Random, self).getstate(), self.gauss_next)
  139.  
  140.     
  141.     def setstate(self, state):
  142.         '''Restore internal state from object returned by getstate().'''
  143.         version = state[0]
  144.         if version == 3:
  145.             (version, internalstate, self.gauss_next) = state
  146.             super(Random, self).setstate(internalstate)
  147.         elif version == 2:
  148.             (version, internalstate, self.gauss_next) = state
  149.             
  150.             try:
  151.                 internalstate = tuple((lambda .0: for x in .0:
  152. long(x) % 0x100000000L)(internalstate))
  153.             except ValueError:
  154.                 e = None
  155.                 raise TypeError, e
  156.  
  157.             super(Random, self).setstate(internalstate)
  158.         else:
  159.             raise ValueError('state with version %s passed to Random.setstate() of version %s' % (version, self.VERSION))
  160.         return version == 3
  161.  
  162.     
  163.     def __getstate__(self):
  164.         return self.getstate()
  165.  
  166.     
  167.     def __setstate__(self, state):
  168.         self.setstate(state)
  169.  
  170.     
  171.     def __reduce__(self):
  172.         return (self.__class__, (), self.getstate())
  173.  
  174.     
  175.     def randrange(self, start, stop = None, step = 1, int = int, default = None, maxwidth = 0x1L << BPF):
  176.         """Choose a random item from range(start, stop[, step]).
  177.  
  178.         This fixes the problem with randint() which includes the
  179.         endpoint; in Python this is usually not what you want.
  180.         Do not supply the 'int', 'default', and 'maxwidth' arguments.
  181.         """
  182.         istart = int(start)
  183.         if istart != start:
  184.             raise ValueError, 'non-integer arg 1 for randrange()'
  185.         istart != start
  186.         if stop is default:
  187.             if istart > 0:
  188.                 if istart >= maxwidth:
  189.                     return self._randbelow(istart)
  190.                 return int(self.random() * istart)
  191.             raise ValueError, 'empty range for randrange()'
  192.         stop is default
  193.         istop = int(stop)
  194.         if istop != stop:
  195.             raise ValueError, 'non-integer stop for randrange()'
  196.         istop != stop
  197.         width = istop - istart
  198.         if step == 1 and width > 0:
  199.             if width >= maxwidth:
  200.                 return int(istart + self._randbelow(width))
  201.             return int(istart + int(self.random() * width))
  202.         if step == 1:
  203.             raise ValueError, 'empty range for randrange() (%d,%d, %d)' % (istart, istop, width)
  204.         step == 1
  205.         istep = int(step)
  206.         if istep != step:
  207.             raise ValueError, 'non-integer step for randrange()'
  208.         istep != step
  209.         if istep > 0:
  210.             n = (width + istep - 1) // istep
  211.         elif istep < 0:
  212.             n = (width + istep + 1) // istep
  213.         else:
  214.             raise ValueError, 'zero step for randrange()'
  215.         if (width > 0) <= 0:
  216.             raise ValueError, 'empty range for randrange()'
  217.         (width > 0) <= 0
  218.         if n >= maxwidth:
  219.             return istart + istep * self._randbelow(n)
  220.         return istart + istep * int(self.random() * n)
  221.  
  222.     
  223.     def randint(self, a, b):
  224.         '''Return random integer in range [a, b], including both end points.
  225.         '''
  226.         return self.randrange(a, b + 1)
  227.  
  228.     
  229.     def _randbelow(self, n, _log = _log, int = int, _maxwidth = 0x1L << BPF, _Method = _MethodType, _BuiltinMethod = _BuiltinMethodType):
  230.         '''Return a random int in the range [0,n)
  231.  
  232.         Handles the case where n has more bits than returned
  233.         by a single call to the underlying generator.
  234.         '''
  235.         
  236.         try:
  237.             getrandbits = self.getrandbits
  238.         except AttributeError:
  239.             pass
  240.  
  241.         if type(self.random) is _BuiltinMethod or type(getrandbits) is _Method:
  242.             k = int(1.00001 + _log(n - 1, 2))
  243.             r = getrandbits(k)
  244.             while r >= n:
  245.                 r = getrandbits(k)
  246.             return r
  247.         if n >= _maxwidth:
  248.             _warn('Underlying random() generator does not supply \nenough bits to choose from a population range this large')
  249.         
  250.         return int(self.random() * n)
  251.  
  252.     
  253.     def choice(self, seq):
  254.         '''Choose a random element from a non-empty sequence.'''
  255.         return seq[int(self.random() * len(seq))]
  256.  
  257.     
  258.     def shuffle(self, x, random = None, int = int):
  259.         '''x, random=random.random -> shuffle list x in place; return None.
  260.  
  261.         Optional arg random is a 0-argument function returning a random
  262.         float in [0.0, 1.0); by default, the standard random.random.
  263.         '''
  264.         if random is None:
  265.             random = self.random
  266.         
  267.         for i in reversed(xrange(1, len(x))):
  268.             j = int(random() * (i + 1))
  269.             x[i] = x[j]
  270.             x[j] = x[i]
  271.         
  272.  
  273.     
  274.     def sample(self, population, k):
  275.         '''Chooses k unique random elements from a population sequence.
  276.  
  277.         Returns a new list containing elements from the population while
  278.         leaving the original population unchanged.  The resulting list is
  279.         in selection order so that all sub-slices will also be valid random
  280.         samples.  This allows raffle winners (the sample) to be partitioned
  281.         into grand prize and second place winners (the subslices).
  282.  
  283.         Members of the population need not be hashable or unique.  If the
  284.         population contains repeats, then each occurrence is a possible
  285.         selection in the sample.
  286.  
  287.         To choose a sample in a range of integers, use xrange as an argument.
  288.         This is especially fast and space efficient for sampling from a
  289.         large population:   sample(xrange(10000000), 60)
  290.         '''
  291.         n = len(population)
  292.         if k <= k:
  293.             pass
  294.         elif not k <= n:
  295.             raise ValueError, 'sample larger than population'
  296.         
  297.         random = self.random
  298.         _int = int
  299.         result = [
  300.             None] * k
  301.         setsize = 21
  302.         if k > 5:
  303.             setsize += 4 ** _ceil(_log(k * 3, 4))
  304.         
  305.         if n <= setsize or hasattr(population, 'keys'):
  306.             pool = list(population)
  307.             for i in xrange(k):
  308.                 j = _int(random() * (n - i))
  309.                 result[i] = pool[j]
  310.                 pool[j] = pool[n - i - 1]
  311.             
  312.         else:
  313.             
  314.             try:
  315.                 selected = set()
  316.                 selected_add = selected.add
  317.                 for i in xrange(k):
  318.                     j = _int(random() * n)
  319.                     while j in selected:
  320.                         j = _int(random() * n)
  321.                     selected_add(j)
  322.                     result[i] = population[j]
  323.             except (TypeError, KeyError):
  324.                 if isinstance(population, list):
  325.                     raise 
  326.                 isinstance(population, list)
  327.                 return self.sample(tuple(population), k)
  328.  
  329.         return result
  330.  
  331.     
  332.     def uniform(self, a, b):
  333.         '''Get a random number in the range [a, b) or [a, b] depending on rounding.'''
  334.         return a + (b - a) * self.random()
  335.  
  336.     
  337.     def triangular(self, low = 0, high = 1, mode = None):
  338.         '''Triangular distribution.
  339.  
  340.         Continuous distribution bounded by given lower and upper limits,
  341.         and having a given mode value in-between.
  342.  
  343.         http://en.wikipedia.org/wiki/Triangular_distribution
  344.  
  345.         '''
  346.         u = self.random()
  347.         c = None if mode is None else (mode - low) / (high - low)
  348.         if u > c:
  349.             u = 1 - u
  350.             c = 1 - c
  351.             low = high
  352.             high = low
  353.         
  354.         return low + (high - low) * (u * c) ** 0.5
  355.  
  356.     
  357.     def normalvariate(self, mu, sigma):
  358.         '''Normal distribution.
  359.  
  360.         mu is the mean, and sigma is the standard deviation.
  361.  
  362.         '''
  363.         random = self.random
  364.         while None:
  365.             u1 = random()
  366.             u2 = 1 - random()
  367.             z = NV_MAGICCONST * (u1 - 0.5) / u2
  368.             zz = z * z / 4
  369.             if zz <= -_log(u2):
  370.                 break
  371.                 continue
  372.             continue
  373.             return mu + z * sigma
  374.  
  375.     
  376.     def lognormvariate(self, mu, sigma):
  377.         """Log normal distribution.
  378.  
  379.         If you take the natural logarithm of this distribution, you'll get a
  380.         normal distribution with mean mu and standard deviation sigma.
  381.         mu can have any value, and sigma must be greater than zero.
  382.  
  383.         """
  384.         return _exp(self.normalvariate(mu, sigma))
  385.  
  386.     
  387.     def expovariate(self, lambd):
  388.         '''Exponential distribution.
  389.  
  390.         lambd is 1.0 divided by the desired mean.  It should be
  391.         nonzero.  (The parameter would be called "lambda", but that is
  392.         a reserved word in Python.)  Returned values range from 0 to
  393.         positive infinity if lambd is positive, and from negative
  394.         infinity to 0 if lambd is negative.
  395.  
  396.         '''
  397.         random = self.random
  398.         u = random()
  399.         while u <= 1e-07:
  400.             u = random()
  401.         return -_log(u) / lambd
  402.  
  403.     
  404.     def vonmisesvariate(self, mu, kappa):
  405.         '''Circular data distribution.
  406.  
  407.         mu is the mean angle, expressed in radians between 0 and 2*pi, and
  408.         kappa is the concentration parameter, which must be greater than or
  409.         equal to zero.  If kappa is equal to zero, this distribution reduces
  410.         to a uniform random angle over the range 0 to 2*pi.
  411.  
  412.         '''
  413.         random = self.random
  414.         if kappa <= 1e-06:
  415.             return TWOPI * random()
  416.         a = 1 + _sqrt(1 + 4 * kappa * kappa)
  417.         b = (a - _sqrt(2 * a)) / 2 * kappa
  418.         r = (1 + b * b) / 2 * b
  419.         while None:
  420.             u1 = random()
  421.             z = _cos(_pi * u1)
  422.             f = (1 + r * z) / (r + z)
  423.             c = kappa * (r - f)
  424.             u2 = random()
  425.             if u2 < c * (2 - c) or u2 <= c * _exp(1 - c):
  426.                 break
  427.                 continue
  428.             continue
  429.             u3 = random()
  430.             if u3 > 0.5:
  431.                 theta = mu % TWOPI + _acos(f)
  432.             else:
  433.                 theta = mu % TWOPI - _acos(f)
  434.         return theta
  435.  
  436.     
  437.     def gammavariate(self, alpha, beta):
  438.         '''Gamma distribution.  Not the gamma function!
  439.  
  440.         Conditions on the parameters are alpha > 0 and beta > 0.
  441.  
  442.         '''
  443.         if alpha <= 0 or beta <= 0:
  444.             raise ValueError, 'gammavariate: alpha and beta must be > 0.0'
  445.         beta <= 0
  446.         random = self.random
  447.         if alpha > 1:
  448.             ainv = _sqrt(2 * alpha - 1)
  449.             bbb = alpha - LOG4
  450.             ccc = alpha + ainv
  451.             while None:
  452.                 u1 = random()
  453.                 if u1 < u1:
  454.                     pass
  455.                 elif not u1 < 1:
  456.                     continue
  457.                 
  458.                 u2 = 1 - random()
  459.                 v = _log(u1 / (1 - u1)) / ainv
  460.                 x = alpha * _exp(v)
  461.                 z = u1 * u1 * u2
  462.                 r = bbb + ccc * v - x
  463.                 if r + SG_MAGICCONST - 4.5 * z >= 0 or r >= _log(z):
  464.                     return x * beta
  465.                 continue
  466.         r >= _log(z)
  467.         if alpha == 1:
  468.             u = random()
  469.             while u <= 1e-07:
  470.                 u = random()
  471.                 continue
  472.                 1e-07
  473.             return -_log(u) * beta
  474.         while None:
  475.             u = random()
  476.             b = (_e + alpha) / _e
  477.             p = b * u
  478.             u1 = random()
  479.             None if p > 1 else None if p <= 1 else 1e-07
  480.             continue
  481.             return x * beta
  482.             return None
  483.  
  484.     
  485.     def gauss(self, mu, sigma):
  486.         '''Gaussian distribution.
  487.  
  488.         mu is the mean, and sigma is the standard deviation.  This is
  489.         slightly faster than the normalvariate() function.
  490.  
  491.         Not thread-safe without a lock around calls.
  492.  
  493.         '''
  494.         random = self.random
  495.         z = self.gauss_next
  496.         self.gauss_next = None
  497.         if z is None:
  498.             x2pi = random() * TWOPI
  499.             g2rad = _sqrt(-2 * _log(1 - random()))
  500.             z = _cos(x2pi) * g2rad
  501.             self.gauss_next = _sin(x2pi) * g2rad
  502.         
  503.         return mu + z * sigma
  504.  
  505.     
  506.     def betavariate(self, alpha, beta):
  507.         '''Beta distribution.
  508.  
  509.         Conditions on the parameters are alpha > 0 and beta > 0.
  510.         Returned values range between 0 and 1.
  511.  
  512.         '''
  513.         y = self.gammavariate(alpha, 1)
  514.         if y == 0:
  515.             return 0
  516.         return y / (y + self.gammavariate(beta, 1))
  517.  
  518.     
  519.     def paretovariate(self, alpha):
  520.         '''Pareto distribution.  alpha is the shape parameter.'''
  521.         u = 1 - self.random()
  522.         return 1 / pow(u, 1 / alpha)
  523.  
  524.     
  525.     def weibullvariate(self, alpha, beta):
  526.         '''Weibull distribution.
  527.  
  528.         alpha is the scale parameter and beta is the shape parameter.
  529.  
  530.         '''
  531.         u = 1 - self.random()
  532.         return alpha * pow(-_log(u), 1 / beta)
  533.  
  534.  
  535.  
  536. class WichmannHill(Random):
  537.     VERSION = 1
  538.     
  539.     def seed(self, a = None):
  540.         '''Initialize internal state from hashable object.
  541.  
  542.         None or no argument seeds from current time or from an operating
  543.         system specific randomness source if available.
  544.  
  545.         If a is not None or an int or long, hash(a) is used instead.
  546.  
  547.         If a is an int or long, a is used directly.  Distinct values between
  548.         0 and 27814431486575L inclusive are guaranteed to yield distinct
  549.         internal states (this guarantee is specific to the default
  550.         Wichmann-Hill generator).
  551.         '''
  552.         if a is None:
  553.             
  554.             try:
  555.                 a = long(_hexlify(_urandom(16)), 16)
  556.             except NotImplementedError:
  557.                 import time
  558.                 a = long(time.time() * 256)
  559.             except:
  560.                 None<EXCEPTION MATCH>NotImplementedError
  561.             
  562.  
  563.         None<EXCEPTION MATCH>NotImplementedError
  564.         if not isinstance(a, (int, long)):
  565.             a = hash(a)
  566.         
  567.         (a, x) = divmod(a, 30268)
  568.         (a, y) = divmod(a, 30306)
  569.         (a, z) = divmod(a, 30322)
  570.         self._seed = (int(x) + 1, int(y) + 1, int(z) + 1)
  571.         self.gauss_next = None
  572.  
  573.     
  574.     def random(self):
  575.         '''Get the next random number in the range [0.0, 1.0).'''
  576.         (x, y, z) = self._seed
  577.         x = 171 * x % 30269
  578.         y = 172 * y % 30307
  579.         z = 170 * z % 30323
  580.         self._seed = (x, y, z)
  581.         return (x / 30269 + y / 30307 + z / 30323) % 1
  582.  
  583.     
  584.     def getstate(self):
  585.         '''Return internal state; can be passed to setstate() later.'''
  586.         return (self.VERSION, self._seed, self.gauss_next)
  587.  
  588.     
  589.     def setstate(self, state):
  590.         '''Restore internal state from object returned by getstate().'''
  591.         version = state[0]
  592.         if version == 1:
  593.             (version, self._seed, self.gauss_next) = state
  594.         else:
  595.             raise ValueError('state with version %s passed to Random.setstate() of version %s' % (version, self.VERSION))
  596.         return version == 1
  597.  
  598.     
  599.     def jumpahead(self, n):
  600.         '''Act as if n calls to random() were made, but quickly.
  601.  
  602.         n is an int, greater than or equal to 0.
  603.  
  604.         Example use:  If you have 2 threads and know that each will
  605.         consume no more than a million random numbers, create two Random
  606.         objects r1 and r2, then do
  607.             r2.setstate(r1.getstate())
  608.             r2.jumpahead(1000000)
  609.         Then r1 and r2 will use guaranteed-disjoint segments of the full
  610.         period.
  611.         '''
  612.         if not n >= 0:
  613.             raise ValueError('n must be >= 0')
  614.         n >= 0
  615.         (x, y, z) = self._seed
  616.         x = int(x * pow(171, n, 30269)) % 30269
  617.         y = int(y * pow(172, n, 30307)) % 30307
  618.         z = int(z * pow(170, n, 30323)) % 30323
  619.         self._seed = (x, y, z)
  620.  
  621.     
  622.     def __whseed(self, x = 0, y = 0, z = 0):
  623.         '''Set the Wichmann-Hill seed from (x, y, z).
  624.  
  625.         These must be integers in the range [0, 256).
  626.         '''
  627.         if type(y) == type(y) and type(z) == type(z):
  628.             pass
  629.         elif not type(z) == int:
  630.             raise TypeError('seeds must be integers')
  631.         
  632.         if x == x and y == y:
  633.             pass
  634.         elif y == z:
  635.             import time
  636.             t = long(time.time() * 256)
  637.             t = int(t & 16777215 ^ t >> 24)
  638.             (t, x) = divmod(t, 256)
  639.             (t, y) = divmod(t, 256)
  640.             (t, z) = divmod(t, 256)
  641.         
  642.         if not z:
  643.             pass
  644.         self._seed = (None, 1 if not x else 1, 1)
  645.         self.gauss_next = None
  646.  
  647.     
  648.     def whseed(self, a = None):
  649.         """Seed from hashable object's hash code.
  650.  
  651.         None or no argument seeds from current time.  It is not guaranteed
  652.         that objects with distinct hash codes lead to distinct internal
  653.         states.
  654.  
  655.         This is obsolete, provided for compatibility with the seed routine
  656.         used prior to Python 2.1.  Use the .seed() method instead.
  657.         """
  658.         if a is None:
  659.             self._WichmannHill__whseed()
  660.             return None
  661.         a = hash(a)
  662.         (a, x) = divmod(a, 256)
  663.         (a, y) = divmod(a, 256)
  664.         (a, z) = divmod(a, 256)
  665.         if not (x + a) % 256:
  666.             pass
  667.         x = 1
  668.         if not (y + a) % 256:
  669.             pass
  670.         y = 1
  671.         if not (z + a) % 256:
  672.             pass
  673.         z = 1
  674.         self._WichmannHill__whseed(x, y, z)
  675.  
  676.  
  677.  
  678. class SystemRandom(Random):
  679.     '''Alternate random number generator using sources provided
  680.     by the operating system (such as /dev/urandom on Unix or
  681.     CryptGenRandom on Windows).
  682.  
  683.      Not available on all systems (see os.urandom() for details).
  684.     '''
  685.     
  686.     def random(self):
  687.         '''Get the next random number in the range [0.0, 1.0).'''
  688.         return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
  689.  
  690.     
  691.     def getrandbits(self, k):
  692.         '''getrandbits(k) -> x.  Generates a long int with k random bits.'''
  693.         if k <= 0:
  694.             raise ValueError('number of bits must be greater than zero')
  695.         k <= 0
  696.         if k != int(k):
  697.             raise TypeError('number of bits should be an integer')
  698.         k != int(k)
  699.         bytes = (k + 7) // 8
  700.         x = long(_hexlify(_urandom(bytes)), 16)
  701.         return x >> bytes * 8 - k
  702.  
  703.     
  704.     def _stub(self, *args, **kwds):
  705.         '''Stub method.  Not used for a system random number generator.'''
  706.         pass
  707.  
  708.     seed = jumpahead = _stub
  709.     
  710.     def _notimplemented(self, *args, **kwds):
  711.         '''Method should not be called for a system random number generator.'''
  712.         raise NotImplementedError('System entropy source does not have state.')
  713.  
  714.     getstate = setstate = _notimplemented
  715.  
  716.  
  717. def _test_generator(n, func, args):
  718.     import time
  719.     print n, 'times', func.__name__
  720.     total = 0
  721.     sqsum = 0
  722.     smallest = 1e+10
  723.     largest = -1e+10
  724.     t0 = time.time()
  725.     for i in range(n):
  726.         x = func(*args)
  727.         total += x
  728.         sqsum = sqsum + x * x
  729.         smallest = min(x, smallest)
  730.         largest = max(x, largest)
  731.     
  732.     t1 = time.time()
  733.     print round(t1 - t0, 3), 'sec,',
  734.     avg = total / n
  735.     stddev = _sqrt(sqsum / n - avg * avg)
  736.     print 'avg %g, stddev %g, min %g, max %g' % (avg, stddev, smallest, largest)
  737.  
  738.  
  739. def _test(N = 2000):
  740.     _test_generator(N, random, ())
  741.     _test_generator(N, normalvariate, (0, 1))
  742.     _test_generator(N, lognormvariate, (0, 1))
  743.     _test_generator(N, vonmisesvariate, (0, 1))
  744.     _test_generator(N, gammavariate, (0.01, 1))
  745.     _test_generator(N, gammavariate, (0.1, 1))
  746.     _test_generator(N, gammavariate, (0.1, 2))
  747.     _test_generator(N, gammavariate, (0.5, 1))
  748.     _test_generator(N, gammavariate, (0.9, 1))
  749.     _test_generator(N, gammavariate, (1, 1))
  750.     _test_generator(N, gammavariate, (2, 1))
  751.     _test_generator(N, gammavariate, (20, 1))
  752.     _test_generator(N, gammavariate, (200, 1))
  753.     _test_generator(N, gauss, (0, 1))
  754.     _test_generator(N, betavariate, (3, 3))
  755.     _test_generator(N, triangular, (0, 1, 0.333333))
  756.  
  757. _inst = Random()
  758. seed = _inst.seed
  759. random = _inst.random
  760. uniform = _inst.uniform
  761. triangular = _inst.triangular
  762. randint = _inst.randint
  763. choice = _inst.choice
  764. randrange = _inst.randrange
  765. sample = _inst.sample
  766. shuffle = _inst.shuffle
  767. normalvariate = _inst.normalvariate
  768. lognormvariate = _inst.lognormvariate
  769. expovariate = _inst.expovariate
  770. vonmisesvariate = _inst.vonmisesvariate
  771. gammavariate = _inst.gammavariate
  772. gauss = _inst.gauss
  773. betavariate = _inst.betavariate
  774. paretovariate = _inst.paretovariate
  775. weibullvariate = _inst.weibullvariate
  776. getstate = _inst.getstate
  777. setstate = _inst.setstate
  778. jumpahead = _inst.jumpahead
  779. getrandbits = _inst.getrandbits
  780. if __name__ == '__main__':
  781.     _test()
  782.  
  783.